package snmp_trap;

import java.io.IOException;

import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;

public class SnmpSendTrap {

	private Snmp snmp;
	private Address targetAddress;
	
	private void init() throws IOException {
		targetAddress = GenericAddress.parse("udp:127.0.0.1/162");
		TransportMapping transport = new DefaultUdpTransportMapping();
		snmp = new Snmp(transport);
		transport.listen();
	}
	
	private void sendPDU() {
		try {
			// ScopedPDU pdu = new ScopedPDU();
			PDU pdu = new PDU();
			pdu.add(new VariableBinding(new OID("1.3.6.1"), new OctetString("SnmpTrap")));
			pdu.add(new VariableBinding(new OID("1.3.6.2"), new OctetString("SnmpTrap2")));
			pdu.add(new VariableBinding(new OID("1.3.6.3"), new OctetString("49:44:3a:31:30:30:2c:44:65:76:69:63:65:54:79:70:65:3a:2d:36:35:35:30:33:2c:c9:e8:b1:b8:c0:eb:cf:df:bb:f2:b2:bb:bf:c9:d3:c3")));
			pdu.add(new VariableBinding(new OID("1.3.6.4"), new OctetString("01:13:68:00:a8:c0:00:69:00:00:00:ac:13:59:04:2c:00:00:00:02:12:00:a8:c0:00:69:00:00:00:ac:13:59:04:2c:03:0c:f3")));
			pdu.add(new VariableBinding(new OID("1.3.6.5"), new OctetString("我是中很难过过热舞")));
			pdu.setType(PDU.TRAP);
			// pdu.setContextEngineID(new OctetString("1.2.2"));
			// pdu.setContextName(new OctetString("contextname"));
			
			CommunityTarget target = new CommunityTarget();
			// UserTarget target = new UserTarget();
			target.setAddress(targetAddress);
			target.setRetries(2);
			target.setTimeout(1500);
			target.setVersion(SnmpConstants.version2c);
			// target.setVersion(SnmpConstants.version3);
			// target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
			// target.setSecurityName(new OctetString("snmpsecurityname"));
			
			snmp.send(pdu, target);
			snmp.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	public static void main(String[] args) {
		try {
			SnmpSendTrap sendTrap = new SnmpSendTrap();
			sendTrap.init();
			sendTrap.sendPDU();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
